<?php
namespace Foam\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\EventManager\EventManagerInterface;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;

class AllergeneController extends AbstractActionController
{
    protected $allergeneTable;
    
    public function setEventManager(EventManagerInterface $events)
    {
        parent::setEventManager($events);
 
        $controller = $this;
        $events->attach('dispatch', function ($e) use ($controller) {
            $controller->layout()->setTemplate('layout/foam');
        }, 100);
 
        return $this;
    }
    
    public function getAllergeneTable()
    {
        if (!$this->allergeneTable) {
            $sm = $this->getServiceLocator();
            $this->allergeneTable = $sm->get('Foam\Model\AllergeneTable');
        }
        return $this->allergeneTable;
    }
    
    public function indexAction()
    {
        return new ViewModel(array(
            'allergenes' => $this->getAllergeneTable()->fetchAll(),
        ));
    }
    
    public function savenewAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $id_allergene = '';
            $libelle = ($request->getPost()->libelle)?$request->getPost()->libelle:'';
        }
        
        $this->getAllergeneTable()->saveNew($id_allergene,$libelle);

        $viewModel = new ViewModel(array(
            'message' => 'Nouvel allergene enregistré',
        ));

        $viewModel->setTerminal(true);
        
        return $viewModel;
    }
    
    public function updateAction()
    {
        $request = $this->getRequest();
        
        if ($request->isPost()) {
            
            $pk = $request->getPost()->pk;
            $name = $request->getPost()->name;
            $value = $request->getPost()->value;
            
            $this->getAllergeneTable()->xeditUpdate($pk, $name, $value);
        }
    }
    
    public function deleteAction()
    {
        $id = $this->params('id');
        $this->getAllergeneTable()->deleteAllergene($id);
        return $this->redirect()->toRoute('foam/default', array('controller'=>'allergene'));
    }
    
    public function xeditableAction()
    {                
        $data = $this->getAllergeneTable()->getList();

        $jsonModel = new JsonModel($data);
        
        return $jsonModel;
    }
}